/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package org.game.netty.server;

import java.util.concurrent.TimeUnit;

import org.game.netty.NettyCodec;

import com.sojoys.artifact.constant.ConfigConstant;
import com.sojoys.artifact.manager.PropManager;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * Echoes back any received data from a client.
 */
public final class NettyServer {

	
	static final Log log = LogFactory.get(NettyServer.class);
//    static final boolean SSL = System.getProperty("ssl") != null;
//    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
	EventLoopGroup bossGroup = null;
	EventLoopGroup workerGroup = null;
	
	// 业务线程池
//	EventExecutorGroup eventExecutorGroup=null;
	// 超时时间
	int timeout = PropManager.getInt(ConfigConstant.SOCKET_TIMEOUT,60000);
	// 逻辑线程数
	int logic_thread_count = PropManager.getInt(ConfigConstant.LOGIC_THREAD_COUNT,4);
	
    public void bind(String host,int port,boolean ssl) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (ssl) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        // Configure the server.
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
//        eventExecutorGroup = new DefaultEventExecutorGroup(logic_thread_count);
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .option(ChannelOption.SO_BACKLOG, 100)	//BACKLOG用于构造服务端套接字ServerSocket对象，标识当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1，Java将使用默认值50。
			 .option(ChannelOption.TCP_NODELAY, true)	//在TCP/IP协议中，无论发送多少数据，总是要在数据前面加上协议头，同时，对方接收到数据，也需要发送ACK表示确认。为了尽可能的利用网络带宽，TCP总是希望尽可能的发送足够大的数据。这里就涉及到一个名为Nagle的算法，该算法的目的就是为了尽可能发送大块数据，避免网络中充斥着许多小数据块。TCP_NODELAY就是用于启用或关于Nagle算法。如果要求高实时性，有数据发送时就马上发送，就将该选项设置为true关闭Nagle算法；如果要减少发送次数减少网络交互，就设置为false等累积一定大小后再发送。默认为false。
			 .option(ChannelOption.SO_REUSEADDR, true)	//端口释放后立即就可以被再次使用
			 .option(ChannelOption.AUTO_READ, true)
//			 .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) 
//			 .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
             .handler(new LoggingHandler(LogLevel.INFO))
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                     if (sslCtx != null) {
                         p.addLast(sslCtx.newHandler(ch.alloc()));
                     }
                     //p.addLast(new LoggingHandler(LogLevel.INFO));
                     p.addLast("codec", new NettyCodec());
                     
                     p.addLast(new IdleStateHandler(0, 0, timeout,TimeUnit.MILLISECONDS));
//                     p.addLast(eventExecutorGroup,new NettyHandler());
                     p.addLast(new HeartbeatHandler());
                     p.addLast(new InterceptHandler());
                     p.addLast(new NettyHandler());
                 }
             });

            // Start the server.
//            b.bind(host,port).sync();
            b.bind(port).sync();
            System.out.println("Netty Server Bind Success! Port -> " + port);
            // Wait until the server socket is closed.
//            f.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
//            bossGroup.shutdownGracefully();
//            workerGroup.shutdownGracefully();
        }
    }
    
    public void shutdown(){
		try {
			bossGroup.shutdownGracefully().sync();
			workerGroup.shutdownGracefully().sync();
			log.info("Netty Server Stop Success!");
		} catch (InterruptedException e) {
			log.error(e);
		}
		
//		eventExecutorGroup.shutdownGracefully();
	}
}